<?php

namespace app\service;


use app\common\model\PrivateChatHistoryModel;
use app\common\model\PrivateChatSessionModel;
use app\common\model\UserModel;
use app\common\model\AdminModel;
use app\common\model\LiveModel;
use app\common\model\ConfigTagModel;
use app\common\model\PrivateChatBanModel;
use think\facade\Cache;
use itbdw\Ip\IpLocation;
use TencentCloud\Bsca\V20210811\BscaClient;

class PrivatechatService extends Service
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @param $admin_role
     * @param $admin_id
     * @return array
     */
    static public function getPrivateList()
    {
        // 查询全部待办会话,会出现重复user_id
        $sessions = self::getAnchorSessionUnread();
        $anchorids = [];
        $chat_history = [];
        foreach ($sessions as $anchorid => $v) {
            $anchorids[] = $anchorid;
        }

        $userlist = UserModel::where('id', 'in', $anchorids)->field('id,nick_name')->select();

        // 获取待办会话直播-私聊历史
        $i = 0;
        foreach ($sessions as $anchorid => $unread) {
            $name = "";
            foreach ($userlist as $user) {
                if ($user->id == $anchorid) {
                    $name = $user->nick_name;
                    break;
                }
            }
            $chat_history[$i]['anchor_id'] = $anchorid;
            $chat_history[$i]['unread'] = $unread;
            $chat_history[$i]['anchor_name'] = $name;
            $i++;
        }
        return ['count' => $i, 'list' => $chat_history];
    }

    //未读session
    static public function getPendingSession($adminId)
    {
        $count = 0;
        $rs = [];
        // foreach ($unreadSession as $i => $v) {
        //     $unread = self::getAnchorUnread($v['id']);
        //     if ($unread > 0) {
        //         $rs[$i]['anchor_id'] = $v['id'];
        //         $rs[$i]['unread'] = $unread;
        //         $rs[$i]['user_id'] = 0;
        //         $count += $unread;
        //     }
        // }
        $anchorIds = AdminModel::get_sub_anchors($adminId);
        foreach ($anchorIds as $anchorId) {
            $unread = self::getAnchorUnread($anchorId);
            if ($unread > 0) {
                $count += $unread;
            }
        }
        return ['count' => $count, 'list' => $rs];
    }


    /**
     * 获取私聊用户id
     * @param $admin_id
     * @return array
     */
    static public function getChatUserIds($admin_id)
    {
        return UserModel::where("FIND_IN_SET($admin_id,chat_admin_ids)")->column('id');
    }

    /**
     * 检测admin账号是否有权限跟用户私聊
     * @param $admin_role
     * @param $admin_id
     * @param $anchor_id 主播id
     * @return array
     */
    static public function checkAdminChat($admin_role, $admin_id, $anchor_id)
    {
        // 权限判断
        // if ($admin_role != 1 && $admin_role != 11) {
        // $chat_admin_ids = explode(',', UserModel::where('id', $anchor_id)->value('chat_admin_ids'));
        // if (!$chat_admin_ids || !in_array($admin_id, $chat_admin_ids)) {
        //     return parent::returnData(1, '你当前没有权限回复该用户聊天');
        // }
        // }
        return parent::returnData(0, 'ok');
    }


    //获取主播的所有 Conversation
    public static function getAnchorConversations($anchor_id, $limit)
    {
        $resp = [];
        $key = "PRIVATECHAT:CONVERSATION:" . $anchor_id;
        $cache = Cache::store('redis')->handler();
        $count = $limit; //每个主播最多取limit条
        $iterator = null;
        do {
            $converSations = $cache->hScan($key, $iterator);
            $processedCount = 0;
            foreach ($converSations as $conversation) {
                $resp[] = json_decode($conversation, true);
                $processedCount++;
                if ($processedCount >= $count) {
                    break;
                }
            }
        } while ($iterator > 0 && $processedCount < $count);
        return $resp;
    }

    //通过$conversationId获得Conversation
    public static function getFromConversation($anchor_id, $conversationId)
    {
        $key = "PRIVATECHAT:CONVERSATION:" . $anchor_id;
        $cache = Cache::store('redis')->handler();
        $result = $cache->hGet($key, $conversationId);
        if ($result) {
            return json_decode($result, true);
        }
        return [];
    }

    //所有主播未读的数量 (主播数量有限，可以用hgetall)
    public static function getAnchorSessionUnread()
    {
        $cache = Cache::store('redis')->handler();
        $key = "PRIVATECHAT:ANCHORSUNREAD";
        $result = $cache->hGetAll($key);
        return $result;
    }

    //获取指定主播未读数
    public static function  getSpecifyAnchorSessionUnread($anchorId)
    {
        $cache = Cache::store('redis')->handler();
        $key = "PRIVATECHAT:ANCHORSUNREAD";
        $unreadNum = $cache->hGet($key, $anchorId);
        $result['anchorId'] = $anchorId;
        $result['unreadNum'] = $unreadNum;
        return $result;
    }


    //主播未读对应的具体用户
    public static function getAnchorSessionUnreadParts($anchor_id, $limit)
    {
        $resp = [];
        $cache = Cache::store('redis')->handler();
        $key = "PRIVATECHAT:ANCHORSUNREADPART:" . $anchor_id;
        $iterator = null;
        $count = $limit; //每个主播最多取limit条
        do {
            $converSations = $cache->hScan($key, $iterator);
            $processedCount = 0;
            foreach ($converSations as $user_id => $unread) {
                $resp[$user_id] = $unread;
                $processedCount++;
                if ($processedCount >= $count) {
                    break;
                }
            }
        } while ($iterator > 0 && $processedCount < $count);
        arsort($resp);
        return $resp;
    }

    //获取某个主播的未读
    public static function getAnchorUnread($anchor_id)
    {
        $cache = Cache::store('redis')->handler();
        $key = "PRIVATECHAT:ANCHORSUNREAD";
        $unread = $cache->hGet($key, $anchor_id);
        return $unread ?? 0;
    }

    public static function alreadyRead($anchor_id, $conversationId)
    {
        $cache = Cache::store('redis')->handler();
        $key = "PRIVATECHAT:ANCHORSUNREADPART:" . $anchor_id;
        $unread = $cache->hGet($key, $conversationId);
        if ($unread > 0) {
            $anchorsUnreadkey = "PRIVATECHAT:ANCHORSUNREAD";
            $anchorUnread = $cache->hGet($anchorsUnreadkey, $anchor_id);
            $leftNum = $anchorUnread - $unread >= 0 ? $anchorUnread - $unread : 0;
            $rs = $cache->HDel($key, $conversationId);
            if ($rs) {
                $cache->hSet($anchorsUnreadkey, $anchor_id, $leftNum);
            }
        }
    }

    static function compareAndSort($num1, $num2)
    {
        // 转换为字符串
        $strNum1 = (string)$num1;
        $strNum2 = (string)$num2;

        // 获取字符串长度
        $len1 = strlen($strNum1);
        $len2 = strlen($strNum2);

        // 比较字符串的每一位
        for ($i = 0; $i < $len1 || $i < $len2; $i++) {
            $digit1 = ($i < $len1) ? (int)$strNum1[$i] : 0;
            $digit2 = ($i < $len2) ? (int)$strNum2[$i] : 0;

            if ($digit1 > $digit2) {
                return [$num2, $num1];
            } elseif ($digit1 < $digit2) {
                return [$num1, $num2];
            }
        }

        // 如果所有位都相等，则返回原始数组
        return [$num1, $num2];
    }

    static function  getUserInfo($userId)
    {
        $cache = Cache::store('redis')->handler();
        // if (!$cache->rawCommand('BF.EXISTS', "id", $userId)) {
        //     return [];
        // }

        $userInfo = $cache->get('USER:FULLINFO:' . $userId);
        if (!$userInfo) {
            if (!$user = UserModel::where('id', $userId)->field('id, nick_name, avatar,tags')->lock()->find()) {
                return [];
            }
            return $user->toArray();
        }
        return json_decode($userInfo, true);
    }

    //获取可管理的主播
    static function getAnchorsInfo($adminId)
    {
        $anchorIds = AdminModel::get_sub_anchors($adminId);
        $specialAnchorIds = self::getSpecialAnchorIds($adminId);
        $anchorsInfo = [];
        foreach ($anchorIds as  $uid) {
            $found = false;
            foreach ($specialAnchorIds['g1'] as $aid) {
                if ($aid == $uid) {
                    $found = true;
                    break;
                }
            }
            if (!$found) {
                foreach ($specialAnchorIds['g2'] as $aid) {
                    if ($aid == $uid) {
                        $found = true;
                        break;
                    }
                }
            }
            if (!$found) {
                foreach ($specialAnchorIds['g3'] as $aid) {
                    if ($aid == $uid) {
                        $found = true;
                        break;
                    }
                }
            }
            if (!$found) {
                foreach ($specialAnchorIds['g4'] as $aid) {
                    if ($aid == $uid) {
                        $found = true;
                        break;
                    }
                }
            }
            if (!$found) {
                foreach ($specialAnchorIds['g5'] as $aid) {
                    if ($aid == $uid) {
                        $found = true;
                        break;
                    }
                }
            }
            if ($found) {
                continue;
            }
            $anchorInfo =  self::getUserInfo($uid);
            if ($anchorInfo) {
                $unread = self::getAnchorUnread($uid);
                $anchorInfo["unread"] = $unread > 0 ? $unread : 0;
                $anchorsInfo[] = $anchorInfo;
            }
        }
        if ($anchorsInfo) {
            usort($anchorsInfo, function ($a, $b) {
                return $b['unread'] - $a['unread'];
            });
        }
        return $anchorsInfo;
    }

    //获取运营需要的特殊主播
    static function getSpecialAnchorIds($adminId)
    {
        $manageAnchorIds = AdminModel::get_sub_anchors($adminId);
        $officialAnchorsIds = config('other.officialAnchors');
        $tags = ConfigTagModel::lists();
        $tagsIds['g1'] = [];  //绿播
        $tagsIds['g2'] = [];  //回放
        $tagsIds['g3'] = [];  //经典
        $tagsIds['g4'] = []; //官方主播
        $tagsIds['g5'] = []; //包含 绿播、回放、经典、官方主播
        $ids = [];
        foreach ($tags as $tag) {
            if ($tag['title'] == "绿色直播") {
                $tagsIds['g1'][$tag['id']] = 1;
                $ids[] = $tag['id'];
            }
            if (strpos($tag['title'], "回放")) {
                $tagsIds['g2'][$tag['id']] = 1;
                $ids[] = $tag['id'];
            }
            if ($tag['title'] == "经典") {
                $tagsIds['g3'][$tag['id']] = 1;
                $ids[] = $tag['id'];
            }
        }
        $result['g1'] = [];
        $result['g2'] = [];
        $result['g3'] = [];
        $result['g4'] = [];
        $result['g5'] = [];
        $lives = LiveModel::where("tag", "in", $ids)->field("anchorId,tag")->select()->toArray();  //取得正在直播的 绿播、回放、经典
        foreach ($lives as $live) {
            foreach ($manageAnchorIds as $anchorId) {
                if ($live['anchorId'] == $anchorId) {
                    if (isset($tagsIds['g1'][$live['tag']])) {
                        $result['g1'][] = $anchorId;
                    }
                    if (isset($tagsIds['g2'][$live['tag']])) {
                        $result['g2'][] = $anchorId;
                        break;
                    }
                    if (isset($tagsIds['g3'][$live['tag']])) {
                        $result['g3'][] = $anchorId;
                        break;
                    }
                    break;
                }
            }
        }
        foreach ($officialAnchorsIds as $aid) {
            foreach ($manageAnchorIds as $anchorId) {
                if ($aid == $anchorId) {
                    $result['g4'][] = $aid;
                    break;
                }
            }
        }
        foreach ($manageAnchorIds as $anchorId) {
            $anchorInfo = self::getUserInfo($anchorId);
            if (!isset($anchorInfo['tags'])) {
                continue;
            }
            if (isset($tagsIds['g1'][$anchorInfo['tags']])) {
                $result['g5'][] = $anchorId;
                continue;
            }
            if (isset($tagsIds['g2'][$anchorInfo['tags']])) {
                $result['g5'][] = $anchorId;
                continue;
            }
            if (isset($tagsIds['g3'][$anchorInfo['tags']])) {
                $result['g5'][] = $anchorId;
                continue;
            }
        }
        return $result;
    }



    static function getSpecialAnchors($adminId)
    {
        $manageAnchorIds = self::getSpecialAnchorIds($adminId);
        $i = 0;
        $result = [];
        if ($manageAnchorIds['g4']) {
            foreach ($manageAnchorIds['g4'] as $uid) {
                $user = self::getUserInfo($uid);
                $unread = self::getAnchorUnread($uid);
                $unread = $unread > 0 ? $unread : 0;
                $result[$i]['unread'] = $unread;
                $result[$i]['nick_name'] = isset($user['nick_name']) ? $user['nick_name'] : $uid;
                $result[$i]['id'] = $uid;
                $i++;
            }
        }
        if ($manageAnchorIds['g1']) {
            $result[$i] = ["nick_name" => "绿色直播", "id" => "g1", "unread" => 0];
            foreach ($manageAnchorIds['g1'] as $uid) {
                $unread = self::getAnchorUnread($uid);
                $uid = $unread > 0 ? $unread : 0;
                $result[$i]['unread'] += $unread;
            }
            $i++;
        }
        if ($manageAnchorIds['g2']) {
            $result[$i] = ["nick_name" => "直播回放", "id" => "g2", "unread" => 0];
            foreach ($manageAnchorIds['g2'] as $uid) {
                $unread = self::getAnchorUnread($uid);
                $uid = $unread > 0 ? $unread : 0;
                $result[$i]['unread'] += $unread; //$unread;
            }
            $i++;
        }
        if ($manageAnchorIds['g3']) {
            $result[$i] = ["nick_name" => "经典", "id" => "g3", "unread" => 0];
            foreach ($manageAnchorIds['g3'] as $uid) {
                $unread = self::getAnchorUnread($uid);
                $uid = $unread > 0 ? $unread : 0;
                $result[$i]['unread'] += $unread;
            }
            $i++;
        }

        return $result;
    }

    static function getAOptPlatformIcon($platform)
    {
        switch (strtolower($platform)) {
            case "web":
                $icon = "/modules/admin/images/icon_web.png";
                break;
            case "ios":
                $icon = "/modules/admin/images/icon_ios.png";
                break;
            case "android":
                $icon = "/modules/admin/images/icon_android.png";
                break;
            default:
                $icon = "/modules/admin/images/icon_web.png";
        }
        return $icon;
    }

    static function processConverSation($converSation, $unread, $anchor)
    {
        if ($converSation) {
            $converSation['_LatestMsgTime'] =  $converSation['LatestMsgTime'];
            $converSation['LatestMsgTime'] = date('m-d H:i:s', $converSation['LatestMsgTime']);
            $converSation['Unread'] = $unread;
            $converSation['AnchorName'] = isset($anchor["nick_name"]) ? $anchor["nick_name"] : "";
            $converSation['Channel'] = isset($converSation["Channel"]) ? $converSation["Channel"] : "";
            $converSation['OptPlatform'] = isset($converSation['OptPlatform']) ? $converSation['OptPlatform'] : "web";
            $converSation['UserAvatar'] = self::getAOptPlatformIcon($converSation['OptPlatform']);
            $loc = IpLocation::getLocation($converSation["UserIp"]);
            $area = count($loc) > 2 ?  mb_substr($loc["area"], 0, 4, 'utf-8') : '未知';
            if (mb_strlen($converSation['UserId']) > 9) {
                $converSation['UserName'] =  '未登录-' . $area;
                $converSation['RsUserName'] =  $converSation['UserName']; //js 右侧显示
            } else {
                $userInfo = self::getUserInfo($converSation['UserId']);
                $converSation['UserName'] = isset($userInfo['id']) ? $userInfo['id'] . '-' . $area : $area;
                $converSation['RsUserName'] =  isset($userInfo['nick_name']) ? $userInfo['nick_name'] . '-' . $area : $area;  //js 右侧显示
            }

            $converSation['Ban'] = PrivateChatBanModel::where("user_id", $converSation['UserId'])->count();
        }
        return $converSation;
    }

    static function getOnlineUser($anchorId)
    {
        $key = "ROOM_ONLINE_USERS:" . $anchorId;
        $cache = Cache::store('redis')->handler();
        $cursor = null;
        $members = [];
        while ($arr  = $cache->sscan($key, $cursor)) {
            foreach ($arr as $id) {
                $members[$id] = 1;
            }
        }
        return $members;
    }
}
